package remote_work.core.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ibm.icu.text.SimpleDateFormat;

import remote_work.dto.InputObject;
import remote_work.dto.OutputObject;
import remote_work.util.DBHelper;

/**
 * @author LiuPing
 *
 * 2018年4月14日
 */
public class MessageService {

	
	/**
	 * 添加留言
	 * 
	 * @param inputObject
	 * @return
	 * @throws Exception
	 */
	public OutputObject addMessage(InputObject inputObject) throws Exception {
		OutputObject outputObject = new OutputObject();
		DBHelper dao = new DBHelper();
		List<Object> params = new ArrayList<>();
		Date date = new Date();
		String insertSql = "insert into message(msgid,msgcontent,msgsender,msgtime,toperson) values (?,?,?,?,?)";
		String msgid = "message"+date.getTime();
		params.add(msgid);
		params.add(inputObject.getValue("msgContent"));
		params.add(inputObject.getValue("msgSender"));
		params.add(inputObject.getValue("msgTime"));
		params.add(inputObject.getValue("toperson"));
		int doUpdate = dao.doUpdate(insertSql, params);
		if (doUpdate <= 0) {
			outputObject.setReturnCode("-1");
			outputObject.setReturnMessage("留言失败");
		}
		outputObject.setReturnMessage(msgid);
		return outputObject;
	}
	
	/**
	 * @param inputObject
	 * @return
	 * @throws Exception
	 */
	public OutputObject getMessages(InputObject inputObject) throws Exception {
		OutputObject outputObject = new OutputObject();
		DBHelper dao = new DBHelper();
		List<Object> params = new ArrayList<>();
		params.add(inputObject.getValue("toperson"));
		params.add(inputObject.getValue("msgsender"));
		String sql = "select b.*,c.username from "
				+ "(select * from message a where a.toperson=? or a.toperson='所有人' or a.msgsender=?) b "
				+ "left join userinfo c on b.toperson=c.userid ";
		outputObject.setBeans(dao.find(sql, params));
		return outputObject;
	}
	
	
	public OutputObject deleteMessage(InputObject inputObject) throws Exception{
		System.out.println("删除留言deleteMessage");
		OutputObject outputObject = new OutputObject();
		DBHelper dao = new DBHelper();
		String sql = "delete from message where msgid=?";
		System.out.println("删除留言msgid"+inputObject.getValue("msgid"));
		List<Object> params = new ArrayList<>();
		params.add(inputObject.getValue("msgid"));
		int result = dao.doUpdate(sql, params);
		outputObject.setReturnCode(String.valueOf(result));
		return outputObject;
	}
}
